package handels

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
	"toffee-candy/cache"
	"toffee-candy/models"
	"toffee-candy/pkg"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSONP(200, gin.H{
			"code": 500,
			"msg":  "字段不为空",
		})
		return
	}
	var user models.User
	redis_key := "redis_login" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount == 3 {
		c.JSONP(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次封禁2小时的业务",
		})
		return
	}
	err := models.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.JSONP(200, gin.H{
			"code": 500,
			"msg":  "无此用户",
		})
		return
	}
	if user.ID == 0 {
		c.JSONP(200, gin.H{
			"code": 500,
			"msg":  "无此用户",
		})
		return
	}
	if user.Password != pkg.Md5Str(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
		if errCount == 2 {
			c.JSONP(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次封禁2小时的业务",
			})
			return
		}
		c.JSONP(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSONP(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
	return
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size
	var user models.User
	models.DB.Offset(offset).Limit(size).Find(&user)
	var total int64
	models.DB.Model(&user).Count(&total)
	c.JSONP(200, gin.H{
		"code":  200,
		"msg":   "登录成功",
		"data":  user,
		"total": total,
	})
	return
}
